package com.iotp.controller.admin.pest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.deser.impl.NullsAsEmptyProvider;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iotp.controller.admin.base.BaseController;
import com.iotp.dao.online_exchange.OnlineExchangeMapper;
import com.iotp.entity.base.CodeEnum;
import com.iotp.entity.base.DataMessage;
import com.iotp.entity.base.KKpager;
import com.iotp.entity.crop.Crop;
import com.iotp.entity.crop_type.CropType;
import com.iotp.entity.disease_area.DiseaseArea;
import com.iotp.entity.disease_name.DiseaseName;
import com.iotp.entity.disease_trait.DiseaseTrait;
import com.iotp.entity.disease_type.DiseaseType;
import com.iotp.entity.equipment.Equipment;
import com.iotp.entity.equipment_data.EquipmentData;
import com.iotp.entity.expert.Expert;
import com.iotp.entity.expert_type.ExpertType;
import com.iotp.entity.knowledge.Knowledge;
import com.iotp.entity.knowledge.KnowledgeWithBLOBs;
import com.iotp.entity.knowledge_type.KnowledgeType;
import com.iotp.entity.leave_message.LeaveMessage;
import com.iotp.entity.msg_config.MsgConfig;
import com.iotp.entity.online_exchange.OnlineExchange;
import com.iotp.entity.time_config.TimeConfig;
import com.iotp.entity.upload_record.UploadRecord;
import com.iotp.entity.user.CommUser;
import com.iotp.entity.userUserRef.TempUser;
import com.iotp.entity.userUserRef.UserUserRef;
import com.iotp.entity.video.Video;
import com.iotp.service.crop.CropService;
import com.iotp.service.crop_type.CropTypeService;
import com.iotp.service.disease_area.DiseaseAreaService;
import com.iotp.service.disease_name.DiseaseNameService;
import com.iotp.service.disease_trait.DiseaseTraitService;
import com.iotp.service.disease_type.DiseaseTypeService;
import com.iotp.service.equipment.EquipmentService;
import com.iotp.service.equipment_data.EquipmentDataService;
import com.iotp.service.expert.ExpertService;
import com.iotp.service.expert_type.ExpertTypeService;
import com.iotp.service.knowledge.KnowledgeService;
import com.iotp.service.knowledge_type.KnowledgeTypeService;
import com.iotp.service.leave_message.LeaveMessageService;
import com.iotp.service.msg_config.MsgConfigService;
import com.iotp.service.online_exchange.OnlineExchangeService;
import com.iotp.service.time_config.TimeConfigService;
import com.iotp.service.upload_record.UploadRecordService;
import com.iotp.service.userUserRef.UserUserRefService;
import com.iotp.service.user_statistics.UserStatisticsService;
import com.iotp.service.video.VideoService;
import com.iotp.utils.common.DateUtils;
import com.iotp.utils.common.WyConstant;
import com.sun.javafx.embed.EmbeddedSceneDTInterface;
import jdk.nashorn.internal.objects.annotations.SpecializedFunction;
import org.apache.commons.io.FileUtils;
import org.omg.PortableInterceptor.INACTIVE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.naming.Name;
import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/sys/pest")
public class PestController extends BaseController {
    @Value("${pic.pastePath}")
    private String pastePath;
    @Value("${pic.url}")
    private String url;
    @Autowired
    private KnowledgeTypeService knowledgeTypeService;
    @Autowired
    private KnowledgeService knowledgeService;
    @Autowired
    private CropService cropService;
    @Autowired
    private DiseaseNameService diseaseNameService;
    @Autowired
    private DiseaseAreaService diseaseAreaService;
    @Autowired
    private DiseaseTraitService diseaseTraitService;
    @Autowired
    private CropTypeService cropTypeService;
    @Autowired
    private DiseaseTypeService diseaseTypeService;
    @Autowired
    private ExpertService expertService;
    @Autowired
    private ExpertTypeService expertTypeService;
    @Autowired
    private LeaveMessageService leaveMessageService;
    @Autowired
    private OnlineExchangeService onlineExchangeService;
    @Autowired
    private UserUserRefService userUserRefService;
    @Autowired
    private MsgConfigService msgConfigService;
    @Autowired
    private TimeConfigService timeConfigService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private EquipmentDataService equipmentDataService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private UploadRecordService uploadRecordService;
    @Autowired
    private UserStatisticsService userStatisticsService;

    private Logger logger = LoggerFactory.getLogger(PestController.class);

    @GetMapping("/addKnowledgeType")
    public String toAddKnowledgeTypePage(){
        return "admin/sys/pest/add_knowledge_type";
    }
    @PostMapping("/addKType")
    @ResponseBody
    public DataMessage addKType(String typeName, String description){
        KnowledgeType add = new KnowledgeType();
        add.setParentId(0L);
        add.setLevel(1);
        add.setTypeName(typeName);
        add.setDescription(description);
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.knowledgeTypeService.addRoot(add);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @GetMapping("/toListKnowledgeList")
    public String toListKnowledgeList(){
        return "admin/sys/pest/list_knowledge_type";
    }

    @PostMapping("/kTypeList")
    @ResponseBody
    public DataMessage selectKType(Integer pageNo, Integer pageSize, String typeName, String typeDesc){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        KnowledgeType query = new KnowledgeType();
        if(!StringUtils.isEmpty(typeName)){
            query.setTypeName(typeName);
        }
        if(!StringUtils.isEmpty(typeDesc)){
            query.setDescription(typeDesc);
        }
        List<KnowledgeType> kTypeList = this.knowledgeTypeService.queryList(query);
        PageInfo<KnowledgeType> pageInfo = new PageInfo<KnowledgeType>(kTypeList);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(kTypeList);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }

    @GetMapping("/kTypeEdit")
    public String toKTypeEdit(String id){
        KnowledgeType k = this.knowledgeTypeService.queryById(Long.parseLong(id));
        request.setAttribute("k", k);
        return "admin/sys/pest/edit_knowledge_type";
    }

    @PostMapping("/editKType")
    @ResponseBody
    public DataMessage editKType(String id, String typeName, String description){
        DataMessage dm = new DataMessage();
        KnowledgeType edit = new KnowledgeType();
        edit.setId(Long.parseLong(id));
        edit.setTypeName(typeName);
        edit.setDescription(description);
        this.knowledgeTypeService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("编辑成功");
        return dm;
    }

    @PostMapping("/delKType")
    @ResponseBody
    public DataMessage delKType(String id){
        DataMessage dm = new DataMessage();
        this.knowledgeTypeService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }
    @PostMapping("/batchDeleteKType")
    @ResponseBody
    public DataMessage batchDeleteKType(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(int i=0;i<arr.length;i++){
            this.knowledgeTypeService.delete(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toAddK")
    public String toAddK(){
        //知识类别
        List<KnowledgeType> types = this.knowledgeTypeService.queryList(new KnowledgeType());
        request.setAttribute("types", types);
        //作物名称
        List<Crop> zwmc = this.cropService.queryList(new Crop());
        request.setAttribute("zwmc", zwmc);
        //病害名称
        List<DiseaseName> bhmc = this.diseaseNameService.queryList(new DiseaseName());
        request.setAttribute("bhmc", bhmc);
        //病害位置
        List<DiseaseArea> bhwz = this.diseaseAreaService.queryList(new DiseaseArea());
        request.setAttribute("bhwz", bhwz);
        //病害特征
        List<DiseaseTrait> bhtz = this.diseaseTraitService.queryList(new DiseaseTrait());
        request.setAttribute("bhtz", bhtz);
        return "admin/sys/pest/add_knowledge";
    }

    @PostMapping("/addK")
    @ResponseBody
    public DataMessage addK(String kName, String kTypeId, String description, String cropIds, String diseaseNameIds,String diseaseAreaIds,String diseaseTraitIds, String synopsis){
        KnowledgeWithBLOBs add = new KnowledgeWithBLOBs();
        add.setkName(kName);
        add.setkTypeId(Long.parseLong(kTypeId));
        add.setSynopsis(synopsis);
//        add.setSource(source);
        add.setDescription(description);
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());

        add.setCropIds(cropIds);
        add.setDiseaseTraitIds(diseaseTraitIds);
        add.setDiseaseNameIds(diseaseNameIds);
        add.setDiseaseAreaIds(diseaseAreaIds);

        add.setState(2);
        this.knowledgeService.add(add);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @GetMapping("/toKList")
    public String toKList(){
        List<KnowledgeType> types = this.knowledgeTypeService.queryList(new KnowledgeType());
        request.setAttribute("types", types);
        return "admin/sys/pest/list_knowledge";
    }

    @PostMapping("/kList")
    @ResponseBody
    public DataMessage kList(Integer pageNo, Integer pageSize, String kName, String typeId){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        KnowledgeWithBLOBs query = new KnowledgeWithBLOBs();
        if(!StringUtils.isEmpty(kName)){
            query.setkName(kName);
        }
        if(!StringUtils.isEmpty(typeId) && !"0".equals(typeId)){
            query.setkTypeId(Long.parseLong(typeId));
        }
        List<KnowledgeWithBLOBs> list = this.knowledgeService.queryList(query);
        PageInfo<KnowledgeWithBLOBs> pageInfo = new PageInfo<KnowledgeWithBLOBs>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }

    @PostMapping("/delK")
    @ResponseBody
    public DataMessage delK(String id){
        DataMessage dm = new DataMessage();
        this.knowledgeService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDeleteK")
    @ResponseBody
    public DataMessage batchDeleteK(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for (int i=0;i<arr.length;i++){
            this.knowledgeService.delete(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toEditK")
    public String toEditK(String id){
        //知识类别
        List<KnowledgeType> types = this.knowledgeTypeService.queryList(new KnowledgeType());
        request.setAttribute("types", types);
        //作物名称
        List<Crop> zwmc = this.cropService.queryList(new Crop());
        request.setAttribute("zwmc", zwmc);
        //病害名称
        List<DiseaseName> bhmc = this.diseaseNameService.queryList(new DiseaseName());
        request.setAttribute("bhmc", bhmc);
        //病害位置
        List<DiseaseArea> bhwz = this.diseaseAreaService.queryList(new DiseaseArea());
        request.setAttribute("bhwz", bhwz);
        //病害特征
        List<DiseaseTrait> bhtz = this.diseaseTraitService.queryList(new DiseaseTrait());
        request.setAttribute("bhtz", bhtz);
        //知识
        KnowledgeWithBLOBs k = this.knowledgeService.queryById(Long.parseLong(id));
        request.setAttribute("k", k);
        return "admin/sys/pest/edit_knowledge";
    }

    @PostMapping("/editK")
    @ResponseBody
    public DataMessage editK(String id,String kName, String kTypeId, String description, String cropIds, String diseaseNameIds,String diseaseAreaIds,String diseaseTraitIds, String synopsis){
        KnowledgeWithBLOBs edit = new KnowledgeWithBLOBs();
        edit.setId(Long.parseLong(id));
        edit.setkName(kName);
        edit.setkTypeId(Long.parseLong(kTypeId));
        edit.setSynopsis(synopsis);
        edit.setDescription(description);
        edit.setCreateTime(System.currentTimeMillis());
        edit.setUpdateTime(System.currentTimeMillis());

        edit.setCropIds(cropIds);
        edit.setDiseaseTraitIds(diseaseTraitIds);
        edit.setDiseaseNameIds(diseaseNameIds);
        edit.setDiseaseAreaIds(diseaseAreaIds);

        edit.setState(2);
        this.knowledgeService.update(edit);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }




    @GetMapping("/toAddCrop")
    public String toAddCrop(){
        List<CropType> cropTypes = this.cropTypeService.queryList(new CropType());
        request.setAttribute("cropTypes", cropTypes);
        return "admin/sys/pest/add_crop";
    }
    @PostMapping("/addCrop")
    @ResponseBody
    public DataMessage addCrop(String name, String typeId){
        DataMessage dm = new DataMessage();
        Crop add = new Crop();
        add.setCropName(name);
        add.setCropTypeId(Long.parseLong(typeId));
        add.setState(1);
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.cropService.add(add);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }
    @GetMapping("/toListCrop")
    public String toListCrop(){
        List<CropType> cropTypes = this.cropTypeService.queryList(new CropType());
        request.setAttribute("cropTypes", cropTypes);
        return "admin/sys/pest/list_crop";
    }

    @PostMapping("/listCrop")
    @ResponseBody
    public DataMessage listCrop(Integer pageNo, Integer pageSize, String name, String typeId){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        Crop query = new Crop();
        if(!StringUtils.isEmpty(name)){
            query.setCropName(name);
        }
        if(!StringUtils.isEmpty(typeId)){
            query.setCropTypeId(Long.parseLong(typeId));
        }
        List<Crop> list = this.cropService.queryList(query);
        PageInfo<Crop> pageInfo = new PageInfo<Crop>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }

    @GetMapping("/toEditCrop")
    public String toEditCrop(String id){
        Crop crop = this.cropService.queryById(Long.parseLong(id));
        request.setAttribute("crop", crop);
        List<CropType> cropTypes = this.cropTypeService.queryList(new CropType());
        request.setAttribute("cropTypes",cropTypes);
        return "admin/sys/pest/edit_crop";
    }

    @PostMapping("/editCrop")
    @ResponseBody
    public DataMessage editCrop(String id, String name, String typeId){
        Crop edit = new Crop();
        edit.setId(Long.parseLong(id));
        edit.setCropName(name);
        edit.setCropTypeId(Long.parseLong(typeId));
        this.cropService.edit(edit);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/delCrop")
    @ResponseBody
    public DataMessage delCrop(String id){
        DataMessage dm = new DataMessage();
        this.cropService.del(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }
    @PostMapping("/batchDeleteCrop")
    @ResponseBody
    public DataMessage batchDeleteCrop(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for (int i=0;i<arr.length;i++){
            this.cropService.del(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toAddCropType")
    public String toAddCropType(){
        return "admin/sys/pest/add_crop_type";
    }

    @PostMapping("/addCropType")
    @ResponseBody
    public DataMessage addCropType(String name){
        DataMessage dm = new DataMessage();
        CropType add = new CropType();
        add.setName(name);
        add.setState(1);
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.cropTypeService.add(add);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @GetMapping("/toListCropType")
    public String toListCropType(){
        return "admin/sys/pest/list_crop_type";
    }
    @PostMapping("/listCropType")
    @ResponseBody
    public DataMessage listCropType(Integer pageNo, Integer pageSize, String name){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        CropType query = new CropType();
        if(!StringUtils.isEmpty(name)){
            query.setName(name);
        }
        List<CropType> list = this.cropTypeService.queryList(query);
        PageInfo<CropType> pageInfo = new PageInfo<CropType>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }

    @GetMapping("/toEditCropType")
    public String toEditCropType(String id){
        CropType cropType = this.cropTypeService.queryById(Long.parseLong(id));
        request.setAttribute("cropType", cropType);
        return "admin/sys/pest/edit_crop_type";
    }

    @PostMapping("/editCropType")
    @ResponseBody
    public DataMessage editCropType(String id, String name){
        DataMessage dm = new DataMessage();
        CropType edit = new CropType();
        edit.setId(Long.parseLong(id));
        edit.setName(name);
        this.cropTypeService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/delCropType")
    @ResponseBody
    public DataMessage delCropType(String id){
        DataMessage dm = new DataMessage();
        this.cropTypeService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelCropType")
    @ResponseBody
    public DataMessage batchDelCropType(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(int i=0;i<arr.length;i++){
            this.cropTypeService.delete(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toAddDArea")
    public String toAddDArea(){
        return "admin/sys/pest/add_disease_area";
    }
    @GetMapping("/toEditDArea")
    public String toEditDArea(String id){
        DiseaseArea da = this.diseaseAreaService.queryById(Long.parseLong(id));
        request.setAttribute("da", da);
        return "admin/sys/pest/edit_disease_area";
    }
    @GetMapping("/toListDArea")
    public String toListDArea(){
        return "admin/sys/pest/list_disease_area";
    }
    @PostMapping("/addDArea")
    @ResponseBody
    public DataMessage addDArea(String name){
        DataMessage dm= new DataMessage();
        DiseaseArea add= new DiseaseArea();
        add.setAreaName(name);
        add.setState(1);
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.diseaseAreaService.add(add);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }
    @PostMapping("/editDArea")
    @ResponseBody
    public DataMessage editDArea(String id, String name){
        DataMessage dm = new DataMessage();
        DiseaseArea edit = new DiseaseArea();
        edit.setId(Long.parseLong(id));
        edit.setAreaName(name);
        edit.setUpdateTime(System.currentTimeMillis());
        this.diseaseAreaService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }
    @PostMapping("/listDArea")
    @ResponseBody
    public DataMessage listDArea(Integer pageNo, Integer pageSize, String name){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        DiseaseArea query = new DiseaseArea();
        if(!StringUtils.isEmpty(name)){
            query.setAreaName(name);
        }
        List<DiseaseArea> list = this.diseaseAreaService.queryList(query);
        PageInfo<DiseaseArea> pageInfo = new PageInfo<DiseaseArea>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }
    @PostMapping("/delDArea")
    @ResponseBody
    public DataMessage delDArea(String id){
        DataMessage dm = new DataMessage();
        this.diseaseAreaService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelDArea")
    @ResponseBody
    public DataMessage batchDelDArea(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(int i=0;i<arr.length;i++){
            this.diseaseAreaService.delete(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }
    @GetMapping("/toAddDName")
    public String toAddDName(){
        List<DiseaseType> dt = this.diseaseTypeService.queryList(new DiseaseType());
        request.setAttribute("dt", dt);
        List<Crop> c = this.cropService.queryList(new Crop());
        request.setAttribute("c", c);
        return "admin/sys/pest/add_disease_name";
    }
    @GetMapping("/toEditDName")
    public String toEditDName(String id){
        DiseaseName dn = this.diseaseNameService.queryById(Long.parseLong(id));
        request.setAttribute("dn", dn);
        List<DiseaseType> dt = this.diseaseTypeService.queryList(new DiseaseType());
        request.setAttribute("dt", dt);
        List<Crop> c = this.cropService.queryList(new Crop());
        request.setAttribute("c", c);
        return "admin/sys/pest/edit_disease_name";
    }
    @GetMapping("/toListDName")
    public String toListDName(){
        List<DiseaseType> dt = this.diseaseTypeService.queryList(new DiseaseType());
        request.setAttribute("dt", dt);
        List<Crop> c = this.cropService.queryList(new Crop());
        request.setAttribute("c", c);
        return "admin/sys/pest/list_disease_name";
    }
    @PostMapping("/addDName")
    @ResponseBody
    public DataMessage addDName(String name, String typeId, String cropId){
        DataMessage dm = new DataMessage();
        DiseaseName add = new DiseaseName();
        add.setName(name);
        add.setTypeId(Long.parseLong(typeId));
        add.setCropId(Long.parseLong(cropId));
        add.setState(1);
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.diseaseNameService.add(add);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @PostMapping("/editDName")
    @ResponseBody
    public DataMessage editDName(String id, String name, String typeId, String cropId){
        DataMessage dm = new DataMessage();
        DiseaseName edit = new DiseaseName();
        edit.setId(Long.parseLong(id));
        edit.setName(name);
        edit.setTypeId(Long.parseLong(typeId));
        edit.setCropId(Long.parseLong(cropId));
        edit.setUpdateTime(System.currentTimeMillis());
        this.diseaseNameService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/listDName")
    @ResponseBody
    public DataMessage listDName(Integer pageNo, Integer pageSize, String name, String typeId){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        DiseaseName query = new DiseaseName();
        if(!StringUtils.isEmpty(name)){
            query.setName(name);
        }
        if(!StringUtils.isEmpty(typeId)){
            query.setTypeId(Long.parseLong(typeId));
        }
        List<DiseaseName> list = this.diseaseNameService.queryList(query);
        PageInfo<DiseaseName> pageInfo = new PageInfo<DiseaseName>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }
    @PostMapping("/delDName")
    @ResponseBody
    public DataMessage delDName(String id){
        DataMessage dm = new DataMessage();
        this.diseaseNameService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelDName")
    @ResponseBody
    public DataMessage batchDelDName(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for (int i=0;i<arr.length;i++){
            this.diseaseNameService.delete(Long.parseLong(arr[i]));
        }
        return dm;
    }

    @GetMapping("/toAddDTrait")
    public String toAddDTrait(){
        return "admin/sys/pest/add_disease_trait";
    }
    @GetMapping("/toEditDTrait")
    public String toEditDTrait(String id){
        DiseaseTrait dt = this.diseaseTraitService.queryById(Long.parseLong(id));
        request.setAttribute("dt", dt);
        return "admin/sys/pest/edit_disease_trait";
    }
    @GetMapping("/toListDTrait")
    public String toListDTrait(){
        return "admin/sys/pest/list_disease_trait";
    }
    @PostMapping("/addDTrait")
    @ResponseBody
    public DataMessage addDTrait(String name){
        DataMessage dm = new DataMessage();
        DiseaseTrait add = new DiseaseTrait();
        add.setTraitName(name);
        add.setState(1);
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.diseaseTraitService.add(add);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }
    @PostMapping("/editDTrait")
    @ResponseBody
    public DataMessage editDTrait(String id, String name){
        DataMessage dm = new DataMessage();
        DiseaseTrait edit = new DiseaseTrait();
        edit.setId(Long.parseLong(id));
        edit.setTraitName(name);
        edit.setUpdateTime(System.currentTimeMillis());
        this.diseaseTraitService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }
    @PostMapping("/listDTrait")
    @ResponseBody
    public DataMessage listDTrait(Integer pageNo, Integer pageSize, String name){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        DiseaseTrait query = new DiseaseTrait();
        if(!StringUtils.isEmpty(name)){
            query.setTraitName(name);
        }
        List<DiseaseTrait> list = this.diseaseTraitService.queryList(query);
        PageInfo<DiseaseTrait> pageInfo = new PageInfo<DiseaseTrait>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }
    @PostMapping("/delDTrait")
    @ResponseBody
    public DataMessage delDTrait(String id){
        DataMessage dm = new DataMessage();
        this.diseaseTraitService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }
    @PostMapping("/batchDelDTrait")
    @ResponseBody
    public DataMessage batchDelDTrait(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(int i=0;i<arr.length;i++){
            this.diseaseTraitService.delete(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    /**
     * 添加专家关联用户
     * @return
     */
    @GetMapping("/toAddExpert")
    public String toAddExpert(){
        List<ExpertType> et = this.expertTypeService.queryList(new ExpertType());
        request.setAttribute("et", et);
        //用户信息
        List<TempUser> tu = this.userUserRefService.queryUserName();
        request.setAttribute("tu", tu);
        return "admin/sys/pest/add_expert";
    }
    @GetMapping("/toEditExpert")
    public String toEditExpert(String id){
        List<ExpertType> et = this.expertTypeService.queryList(new ExpertType());
        request.setAttribute("et", et);
        Expert e = this.expertService.queryById(Long.parseLong(id));
        request.setAttribute("e", e);
        //用户信息
        List<TempUser> tu = this.userUserRefService.queryUserName();
        request.setAttribute("tu", tu);
        return "admin/sys/pest/edit_expert";
    }
    @GetMapping("/toListExpert")
    public String toListExpert(){
        List<ExpertType> et = this.expertTypeService.queryList(new ExpertType());
        request.setAttribute("et", et);
        return "admin/sys/pest/list_expert";
    }
    @PostMapping("/addExpert")
    @ResponseBody
    public DataMessage addExpert(String name, String age, String position, String typeId, String typeName, String introduction, MultipartFile headImg, String userId) throws Exception{
        Expert add = new Expert();
        add.setName(name);
        add.setAge(Integer.parseInt(age));
        add.setPosition(position);
        add.setExpertType(Long.parseLong(typeId));
        add.setTypeName(typeName);
        add.setIntroduction(introduction);
        add.setUserId(Long.parseLong(userId));
        add.setState(1);

        String realPath = pastePath;
        String imgPath = new SimpleDateFormat("yyyyMM").format(new Date())+"/"+System.currentTimeMillis()+"."+headImg.getOriginalFilename().split("\\.")[1];
        FileUtils.copyInputStreamToFile(headImg.getInputStream(), new File(realPath, imgPath));

        add.setHeadImgUrl(url+imgPath);
        add.setCreatTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.expertService.add(add);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;

    }
    @PostMapping("/editExpert")
    @ResponseBody
    public DataMessage editExpert(String id, String name, String age, String position, String introduction,String typeId, String typeName,String userId){
        DataMessage dm = new DataMessage();
        Expert edit = new Expert();
        edit.setId(Long.parseLong(id));
        edit.setName(name);
        edit.setAge(Integer.parseInt(age));
        edit.setPosition(position);
        edit.setIntroduction(introduction);
        edit.setUpdateTime(System.currentTimeMillis());
        edit.setTypeName(typeName);
        edit.setExpertType(Long.parseLong(typeId));
        edit.setUserId(Long.parseLong(userId));
        this.expertService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/listExpert")
    @ResponseBody
    public DataMessage listExpert(Integer pageNo, Integer pageSize, String name, String typeId){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        Expert query = new Expert();
        if(!StringUtils.isEmpty(name)){
            query.setName(name);
        }
        if(!StringUtils.isEmpty(typeId) && !"0".equals(typeId)){
            query.setExpertType(Long.parseLong(typeId));
        }
        List<Expert> list = this.expertService.queryList(query);
        PageInfo<Expert> pageInfo = new PageInfo<Expert>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }

    @PostMapping("/delExpert")
    @ResponseBody
    public DataMessage delExpert(String id){
        DataMessage dm = new DataMessage();
        this.expertService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelExpert")
    @ResponseBody
    public DataMessage batchDelExpert(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(int i=0;i<arr.length;i++){
            this.expertService.delete(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toAddMsg")
    public String toAddMsg(){
        return "admin/sys/pest/add_msg";
    }
    @GetMapping("/toEditMsg")
    public String toEditMsg(String id){
        MsgConfig m = this.msgConfigService.queryById(Long.parseLong(id));
        request.setAttribute("m", m);
        return "admin/sys/pest/edit_msg";
    }
    @GetMapping("/toListMsg")
    public String toListMsg(){
        return "admin/sys/pest/list_msg";
    }

    @PostMapping("/addMsg")
    @ResponseBody
    public DataMessage addMsg(String type, String content){
        MsgConfig add = new MsgConfig();
        add.setType(Integer.parseInt(type));
        add.setContent(content);
        add.setState(1);
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.msgConfigService.add(add);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @PostMapping("/editMsg")
    @ResponseBody
    public DataMessage editMsg(String id, String type, String content){
        DataMessage dm = new DataMessage();
        MsgConfig edit = new MsgConfig();
        edit.setId(Long.parseLong(id));
        edit.setType(Integer.parseInt(type));
        edit.setContent(content);
        edit.setUpdateTime(System.currentTimeMillis());
        this.msgConfigService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/listMsg")
    @ResponseBody
    public DataMessage listMsg(Integer pageNo, Integer pageSize, String type){
        DataMessage dm = new DataMessage();
        MsgConfig query = new MsgConfig();
        if(!StringUtils.isEmpty(type) && !"0".equals(type)){
            query.setType(Integer.parseInt(type));
        }
        List<MsgConfig> list = this.msgConfigService.queryByList(query);


        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));

        PageInfo<MsgConfig> pageInfo = new PageInfo<MsgConfig>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());

        return dm;
    }

    @PostMapping("/delMsg")
    @ResponseBody
    public DataMessage delMsg(String id){
        this.msgConfigService.delete(Long.parseLong(id));
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelMsg")
    @ResponseBody
    public DataMessage batchDelMsg(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(String id : arr){
            this.msgConfigService.delete(Long.parseLong(id));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toAddExpertType")
    public String toAddExpertType(){
        return "admin/sys/pest/add_expert_type";
    }
    @GetMapping("/toEditExpertType")
    public String toEditExpertType(String id){
        ExpertType et = this.expertTypeService.queryById(Long.parseLong(id));
        request.setAttribute("et", et);
        return "admin/sys/pest/edit_expert_type";
    }
    @GetMapping("/toListExpertType")
    public String toListExpertType(){
        return "admin/sys/pest/list_expert_type";
    }
    @PostMapping("/addExpertType")
    @ResponseBody
    public DataMessage addExpertType(String name){
        DataMessage dm = new DataMessage();
        ExpertType et = new ExpertType();
        et.setName(name);
        et.setState(1);
        et.setCreateTime(System.currentTimeMillis());
        et.setUpdateTime(System.currentTimeMillis());
        this.expertTypeService.add(et);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }
    @PostMapping("/editExpertType")
    @ResponseBody
    public DataMessage editExpertType(String id, String name){
        DataMessage dm = new DataMessage();
        ExpertType edit = new ExpertType();
        edit.setId(Long.parseLong(id));
        edit.setName(name);
        edit.setUpdateTime(System.currentTimeMillis());
        this.expertTypeService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }
    @PostMapping("/listExpertType")
    @ResponseBody
    public DataMessage listExpertType(Integer pageNo, Integer pageSize, String name){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        ExpertType query = new ExpertType();
        if(!StringUtils.isEmpty(name)){
            query.setName(name);
        }
        List<ExpertType> list = this.expertTypeService.queryList(query);
        PageInfo<ExpertType> pageInfo = new PageInfo<ExpertType>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }

    @PostMapping("/delExpertType")
    @ResponseBody
    public DataMessage delExpertType(String id){
        DataMessage dm = new DataMessage();
        this.expertTypeService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelExpertType")
    @ResponseBody
    public DataMessage batchDelExpertType(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(int i=0;i<arr.length;i++){
            this.expertTypeService.delete(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toEditLeaveM")
    public String toEditLeaveM(String id){
        LeaveMessage l = this.leaveMessageService.queryById(Long.parseLong(id));
        request.setAttribute("l", l);
        return "admin/sys/pest/edit_leave_message";
    }

    @GetMapping("/toListLeaveM")
    public String toListLeaveM(){
        List<Expert> e = this.expertService.queryList(new Expert());
        request.setAttribute("e", e);
        List<DiseaseType> dt = this.diseaseTypeService.queryList(new DiseaseType());
        request.setAttribute("dt", dt);
        return "admin/sys/pest/list_leave_message";
    }

    @PostMapping("/editLeaveM")
    @ResponseBody
    public DataMessage editLeaveM(String id, String replyContent){
        DataMessage dm = new DataMessage();
        LeaveMessage edit = new LeaveMessage();
        edit.setId(Long.parseLong(id));
        edit.setReplyContent(replyContent);
        edit.setUpdateTime(System.currentTimeMillis());
        this.leaveMessageService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/listLeaveM")
    @ResponseBody
    public DataMessage listLeaveM(Integer pageNo, Integer pageSize, String expertId, String typeId){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        LeaveMessage query = new LeaveMessage();
        if(!StringUtils.isEmpty(expertId)){
            query.setConsultExpertId(Long.parseLong(expertId));
        }
        if(!StringUtils.isEmpty(typeId)){
            query.setPestType(typeId);
        }
        List<LeaveMessage> list = this.leaveMessageService.queryList(query);
        PageInfo<LeaveMessage> pageInfo = new PageInfo<LeaveMessage>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }

    @PostMapping("/delLeaveM")
    @ResponseBody
    public DataMessage delLeaveM(String id){
        DataMessage dm = new DataMessage();
        this.leaveMessageService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }
    @PostMapping("/batchDelLeaveM")
    @ResponseBody
    public DataMessage batchDelLeaveM(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(int i=0;i<arr.length;i++){
            this.leaveMessageService.delete(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toEditOnlineE")
    public String toEditOnlineE(String id){
        OnlineExchange oe = this.onlineExchangeService.queryById(Long.parseLong(id));
        request.setAttribute("oe", oe);
        return "admin/sys/pest/edit_online_exchange";
    }
    @GetMapping("/toListOnlineE")
    public String toListOnlineE(){
        return "admin/sys/pest/list_online_exchange";
    }
    @PostMapping("/editOnlineE")
    @ResponseBody
    public DataMessage editOnlineE(String id, String replyContent){
        DataMessage dm = new DataMessage();
        OnlineExchange edit = new OnlineExchange();
        edit.setId(Long.parseLong(id));
        edit.setReplyContent(replyContent);
        edit.setUpdateTime(System.currentTimeMillis());
        this.onlineExchangeService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/listOnlineE")
    @ResponseBody
    public DataMessage listOnlineE(Integer pageNo, Integer pageSize, String consultContent){
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        OnlineExchange query = new OnlineExchange();
        if(!StringUtils.isEmpty(consultContent)){
            query.setConsultContent(consultContent);
        }
        List<OnlineExchange> list = this.onlineExchangeService.queryList(query);
        PageInfo<OnlineExchange> pageInfo = new PageInfo<OnlineExchange>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());

        return dm;
    }

    @PostMapping("/delOnlineE")
    @ResponseBody
    public DataMessage delOnlineE(String id){
        DataMessage dm = new DataMessage();
        this.onlineExchangeService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelOnline")
    @ResponseBody
    public DataMessage batchDelOnline(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(int i=0;i<arr.length;i++){
            this.onlineExchangeService.delete(Long.parseLong(arr[i]));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    /**
     * 接在首页数据
     * @return
     */
    @PostMapping("/getWelcomeInfo")
    @ResponseBody
    public DataMessage getWelcomeInfo(){
        DataMessage dm = new DataMessage();
        CommUser user = (CommUser) request.getSession().getAttribute(CodeEnum.当前用户.msg);
        //用户数
        List<UserUserRef> u_list = this.userUserRefService.queryByCondition(new UserUserRef());
        //专家数
        List<Expert> e_list = this.expertService.queryList(new Expert());
        //留言数
        List<LeaveMessage> l_list = this.leaveMessageService.queryList(new LeaveMessage());
        //文章数
        List<KnowledgeWithBLOBs> k_list = this.knowledgeService.queryList(new KnowledgeWithBLOBs());

        String str = user.getUserNameCn()+","+(u_list == null ? 0 : u_list.size())+","+(e_list == null ? 0 : e_list.size())+
                ","+(l_list == null ? 0 : l_list.size())+","+(k_list == null ? 0 : k_list.size());
        dm.setData(str);
        return dm;
    }

    @GetMapping("/toAddTime")
    public String toAddTime(){
        return "admin/sys/pest/add_time";
    }
    @GetMapping("/toEditTime")
    public String toEditTime(String id){
        TimeConfig t = this.timeConfigService.queryById(Long.parseLong(id));
        request.setAttribute("t", t);
        return "admin/sys/pest/edit_time";
    }
    @GetMapping("/toListTime")
    public String toListTime(){
        return "admin/sys/pest/list_time";
    }
    @PostMapping("/addTime")
    @ResponseBody
    public DataMessage addTime(String xzTime){
        TimeConfig add = new TimeConfig();
        add.setXzTime(Integer.parseInt(xzTime));
        add.setUpdateTime(System.currentTimeMillis());
        add.setCreateTime(System.currentTimeMillis());
        this.timeConfigService.add(add);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @PostMapping("/editTime")
    @ResponseBody
    public DataMessage editTime(String id, String xzTime){
        DataMessage dm = new DataMessage();
        TimeConfig edit = new TimeConfig();
        edit.setId(Long.parseLong(id));
        edit.setXzTime(Integer.parseInt(xzTime));
        this.timeConfigService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/listTime")
    @ResponseBody
    public DataMessage listTime(Integer pageNo, Integer pageSize, String xzTime){
        DataMessage dm = new DataMessage();
        TimeConfig query = new TimeConfig();
        if(!StringUtils.isEmpty(xzTime)){
            query.setXzTime(Integer.parseInt(xzTime));
        }
        List<TimeConfig> list = this.timeConfigService.queryByList(query);

        PageInfo<TimeConfig> pageInfo = new PageInfo<TimeConfig>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());

        return dm;
    }

    @PostMapping("/delTime")
    @ResponseBody
    public DataMessage delTime(String id){
        DataMessage dm = new DataMessage();
        this.timeConfigService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelTime")
    @ResponseBody
    public DataMessage batchDelTime(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(String id : arr){
            this.timeConfigService.delete(Long.parseLong(id));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toAddEq")
    public String toAddEq(){
        return "admin/sys/pest/add_eq";
    }
    @GetMapping("/toEditEq")
    public String toEditEq(String id){
        Equipment e = this.equipmentService.queryById(Long.parseLong(id));
        request.setAttribute("e", e);
        return "admin/sys/pest/edit_eq";
    }
    @GetMapping("/toListEq")
    public String toListEq(){
        return "admin/sys/pest/list_eq";
    }

    @PostMapping("/addEq")
    @ResponseBody
    public DataMessage addEq(String ssArea, String fzArea, String jd, String wd, String name, String number, String type,
                             String model, String port, String ip, String yz, String state){
        DataMessage dm = new DataMessage();
        Equipment add = new Equipment();
        add.setState(Integer.parseInt(state));
        add.setSsArea(ssArea);
        add.setFzArea(fzArea);
        add.setJd(jd);
        add.setWd(wd);
        add.setName(name);
        add.setNumber(number);
        add.setType(type);
        add.setModel(model);
        add.setPort(port);
        add.setIp(ip);
        add.setYz(Integer.parseInt(yz));
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.equipmentService.add(add);
        dm.setResult(0);
        dm.setMessage("添加成功");
        dm.setData(null);
        return dm;
    }

    @PostMapping("/editEq")
    @ResponseBody
    public DataMessage editEq(String id, String ssArea, String fzArea, String jd, String wd, String name, String number, String type,
                              String model, String port, String ip, String yz){
        DataMessage dm = new DataMessage();
        Equipment edit = new Equipment();
        edit.setId(Long.parseLong(id));
        edit.setState(1);
        edit.setSsArea(ssArea);
        edit.setFzArea(fzArea);
        edit.setJd(jd);
        edit.setWd(wd);
        edit.setName(name);
        edit.setNumber(number);
        edit.setType(type);
        edit.setModel(model);
        edit.setPort(port);
        edit.setIp(ip);
        edit.setYz(Integer.parseInt(yz));
        this.equipmentService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("编辑成功");
        return dm;
    }

    @PostMapping("listEq")
    @ResponseBody
    public DataMessage listEq(Integer pageNo, Integer pageSize, String name, String ssArea){
        DataMessage dm = new DataMessage();
        Equipment query = new Equipment();
        if(!StringUtils.isEmpty(name)){
            query.setName(name);
        }
        if(!StringUtils.isEmpty(ssArea)){
            query.setSsArea(ssArea);
        }
        List<Equipment> list = this.equipmentService.queryByList(query);

        PageInfo<Equipment> pageInfo = new PageInfo<Equipment>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());

        return dm;
    }

    @PostMapping("/delEq")
    @ResponseBody
    public DataMessage delEq(String id){
        DataMessage dm = new DataMessage();
        this.equipmentService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/delBatchEq")
    @ResponseBody
    public DataMessage delBatchEq(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(String id : arr){
            this.equipmentService.delete(Long.parseLong(id));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toAddEqData")
    public String toAddEqData(){
        List<Equipment> e = this.equipmentService.queryByList(new Equipment());
        request.setAttribute("e", e);
        return "admin/sys/pest/add_eq_data";
    }

    @GetMapping("/toEditEqData")
    public String toEditEqData(String id){
        List<Equipment> e1 = this.equipmentService.queryByList(new Equipment());
        request.setAttribute("e1", e1);
        EquipmentData e = this.equipmentDataService.queryById(Long.parseLong(id));
        request.setAttribute("e", e);
        return "admin/sys/pest/edit_eq_data";
    }

    @GetMapping("/toListEqData")
    public String toListEqData(){
        return "admin/sys/pest/list_eq_data";
    }

    @PostMapping("/addEqData")
    @ResponseBody
    public DataMessage addEqData(String type, String state, String equipmentId,String content, String yz){
        Equipment e = this.equipmentService.queryById(Long.parseLong(equipmentId));
        EquipmentData add = new EquipmentData();
        add.setType(Integer.parseInt(type));
        add.setState(Integer.parseInt(state));
        add.setEquipmentId(Long.parseLong(equipmentId));
        add.setSsArea(e.getSsArea());
        add.setModel(e.getModel());
        add.setEquipmentYz(e.getYz());

        add.setContent(content);
        add.setYz(Integer.parseInt(yz));
        add.setUpdateTime(System.currentTimeMillis());
        add.setCreateTime(System.currentTimeMillis());
        this.equipmentDataService.add(add);

        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @PostMapping("/editEqData")
    @ResponseBody
    public DataMessage editEqData(String id,String type, String state, String equipmentId,String content, String yz){
        Equipment e = this.equipmentService.queryById(Long.parseLong(equipmentId));
        EquipmentData add = new EquipmentData();
        add.setType(Integer.parseInt(type));
        add.setState(Integer.parseInt(state));
        add.setEquipmentId(Long.parseLong(equipmentId));
        add.setSsArea(e.getSsArea());
        add.setModel(e.getModel());
        add.setEquipmentYz(e.getYz());

        add.setContent(content);
        add.setYz(Integer.parseInt(yz));
        add.setUpdateTime(System.currentTimeMillis());
        add.setCreateTime(System.currentTimeMillis());
        add.setId(Long.parseLong(id));
        this.equipmentDataService.update(add);

        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("编辑成功");
        return dm;
    }

    @PostMapping("/listEqData")
    @ResponseBody
    public DataMessage listEqData(Integer pageNo, Integer pageSize, String type, String ssArea){
        DataMessage dm = new DataMessage();

        EquipmentData query = new EquipmentData();
        if(!StringUtils.isEmpty(type) && !"0".equals(type)){
            query.setType(Integer.parseInt(type));
        }
        if(!StringUtils.isEmpty(ssArea)){
            query.setSsArea(ssArea);
        }
        List<EquipmentData> list = this.equipmentDataService.queryByList(query);

        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        PageInfo<EquipmentData> pageInfo = new PageInfo<EquipmentData>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());

        return dm;
    }

    @PostMapping("/delEqData")
    @ResponseBody
    public DataMessage delEqData(String id){
        DataMessage dm = new DataMessage();
        this.equipmentDataService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelEqData")
    @ResponseBody
    public DataMessage batchDelEqData(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(String id : arr){
            this.equipmentDataService.delete(Long.parseLong(id));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @GetMapping("/toAddDType")
    public String toAddDType(){
        return "admin/sys/pest/add_disease_type";
    }
    @GetMapping("/toEditDType")
    public String toEditDType(String id){
        DiseaseType d = this.diseaseTypeService.queryById(Long.parseLong(id));
        request.setAttribute("d", d);
        return "admin/sys/pest/edit_disease_type";
    }
    @GetMapping("/toListDType")
    public String toListDType(){
        return "admin/sys/pest/list_disease_type";
    }

    @PostMapping("/addDType")
    @ResponseBody
    public DataMessage addDType(String typeName){
        DataMessage dm = new DataMessage();
        DiseaseType add = new DiseaseType();
        add.setTypeName(typeName);
        add.setState(1);
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        this.diseaseTypeService.add(add);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @PostMapping("/editDType")
    @ResponseBody
    public DataMessage editDType(String id, String typeName){
        DataMessage dm = new DataMessage();
        DiseaseType edit = new DiseaseType();
        edit.setId(Long.parseLong(id));
        edit.setTypeName(typeName);
        this.diseaseTypeService.update(edit);
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/listDType")
    @ResponseBody
    public DataMessage listDType(Integer pageNo, Integer pageSize, String typeName){
        DataMessage dm = new DataMessage();
        DiseaseType query = new DiseaseType();
        if(!StringUtils.isEmpty(typeName)){
            query.setTypeName(typeName);
        }
        List<DiseaseType> list = this.diseaseTypeService.queryList(query);

        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        PageInfo<DiseaseType> pageInfo = new PageInfo<DiseaseType>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());

        return dm;
    }

    @PostMapping("/delDType")
    @ResponseBody
    public DataMessage delDType(String id){
        DataMessage dm = new DataMessage();
        this.diseaseTypeService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelDType")
    @ResponseBody
    public DataMessage batchDelDType(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(String id : arr){
            this.diseaseTypeService.delete(Long.parseLong(id));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }
    @GetMapping("/toAddVideo")
    public String toAddVideo(){
        return "admin/sys/pest/add_video";
    }
    @GetMapping("/toEditVideo")
    public String toEditVideo(String id){
        Video v = this.videoService.selectById(Long.parseLong(id));
        request.setAttribute("v", v);
        return "admin/sys/pest/edit_video";
    }
    @GetMapping("/toListVideo")
    public String toListVideo(){
        return "admin/sys/pest/list_video";
    }

    @PostMapping("/addVideo")
    @ResponseBody
    public DataMessage addVideo(String videoName, String videoDesc, MultipartFile pic, String newName){
        Video add = new Video();
        add.setVideoName(videoName);
        add.setVideoDesc(videoDesc);
        add.setVideoUrl(url+new SimpleDateFormat("yyyyMM").format(new Date())+"/"+newName);
        add.setCreateTime(System.currentTimeMillis());
        String realPath = pastePath;
        String imgPath = new SimpleDateFormat("yyyyMM").format(new Date())+"/"+System.currentTimeMillis()+"."+pic.getOriginalFilename().split("\\.")[1];
        try {
            FileUtils.copyInputStreamToFile(pic.getInputStream(), new File(realPath, imgPath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        add.setVideoPicUrl(url+imgPath);
        this.videoService.add(add);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @PostMapping("/editVideo")
    @ResponseBody
    public DataMessage editVideo(String id,String videoName, String videoDesc){
        Video edit = new Video();
        edit.setId(Long.parseLong(id));
        edit.setVideoName(videoName);
        edit.setVideoDesc(videoDesc);
        this.videoService.update(edit);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("修改成功");
        return dm;
    }

    @PostMapping("/listVideo")
    @ResponseBody
    public DataMessage listVideo(Integer pageNo, Integer pageSize, String videoName){
        DataMessage dm = new DataMessage();
        Video query = new Video();
        if(!StringUtils.isEmpty(videoName)){
            query.setVideoName(videoName);
        }
        List<Video> list = this.videoService.selectList(query);

        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        PageInfo<Video> pageInfo = new PageInfo<Video>(list);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(list);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());

        return dm;
    }

    @PostMapping("/delVideo")
    @ResponseBody
    public DataMessage delVideo(String id){
        DataMessage dm = new DataMessage();
        this.videoService.delete(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }

    @PostMapping("/batchDelVideo")
    @ResponseBody
    public DataMessage batchDelVideo(String ids){
        DataMessage dm = new DataMessage();
        String[] arr = ids.split(",");
        for(String id : arr){
            this.videoService.delete(Long.parseLong(id));
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("删除成功");
        return dm;
    }
    /**
     * 获取已上传文件的大小
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadSize", method = RequestMethod.POST)
    @ResponseBody
    public Long uploadSize(HttpServletRequest request) {
        logger.error("获取已上传文件的大小"+request.getParameter("size"));
        String name = request.getParameter("name");
        String newName = request.getParameter("newName");
        Long size = Long.parseLong(request.getParameter("size"));
        try {

//            String str = RedisUtil.getJedis().get(newName);
//            String str = request.getSession().getAttribute(newName)+"";
            UploadRecord u = this.uploadRecordService.queryByName(newName);
            String str = u == null ?"":u.getContent();

            UploadedFileInfo uploadedFileInfo = null;

            // 如果首次上传，已上传大小为 0
            if (null == str || "".equals(str) || "null".equals(str) ) {
                uploadedFileInfo = new UploadedFileInfo();
//                request.setAttribute(newName, JSON.toJSONString(uploadedFileInfo));
                UploadRecord add = new UploadRecord();
                add.setName(newName);
                add.setContent(JSON.toJSONString(uploadedFileInfo));
                add.setCreateTime(System.currentTimeMillis());
                this.uploadRecordService.add(add);
//                RedisUtil.getJedis().set(newName, JSON.toJSONString(uploadedFileInfo));
//                RedisUtil.getJedis().close();
                return 0L;
            }

            uploadedFileInfo = JSON.parseObject(str, UploadedFileInfo.class);

//            RedisUtil.getJedis().close();
            //已经全部上传
            if(size <= uploadedFileInfo.getSize()){
                logger.error("上传完成");
            }
            //UploadUtil.getFileInfo(uploadedFileInfo.getFileId());
            return uploadedFileInfo.getSize();
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }

    }
    /**
     * 文件上传
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadFile1", method = RequestMethod.POST)
    @ResponseBody
    public int upload1(HttpServletRequest request) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> t = multiRequest.getFileNames();
        MultipartFile fileDetail = multiRequest.getFile(t.next());
        String name = request.getParameter("name");//文件名称
        String newName = request.getParameter("newName");//加时间戳后的文件名称
        //System.out.println(request.getSession().getAttribute(newName));
        UploadRecord uploadRecord = this.uploadRecordService.queryByName(newName);
//        UploadedFileInfo uploadedFileInfo = JSON.parseObject(RedisUtil.getJedis().get(newName), UploadedFileInfo.class);
        UploadedFileInfo uploadedFileInfo = JSON.parseObject(uploadRecord.getContent(), UploadedFileInfo.class);
        //设置过期时间
//        RedisUtil.getJedis().expire(newName, 600);
        uploadedFileInfo.setFileName(newName);
//        String path = MlConstant.GIF_PATH+"/"+new SimpleDateFormat("yyyyMM").format(new Date());
        String realPath = pastePath;
        String imgPath = realPath+new SimpleDateFormat("yyyyMM").format(new Date());
        File file = new File(imgPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }

        RandomAccessFile randomFile = null;
        try {
            randomFile = new RandomAccessFile(imgPath+"/"+newName, "rw");
            System.out.println("文件路径="+imgPath+"/"+newName);
            randomFile.seek(randomFile.length());
            randomFile.write(fileDetail.getBytes());

            uploadedFileInfo.setLocalPath(imgPath+"/"+name);
            uploadedFileInfo.setSize(randomFile.length());
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                randomFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 将上传文件信息保存到redis
        //request.getSession().setAttribute(newName, JSON.toJSONString(uploadedFileInfo));
        UploadRecord add = new UploadRecord();
        add.setName(newName);
        add.setContent(JSON.toJSONString(uploadedFileInfo));
        add.setCreateTime(System.currentTimeMillis());
        this.uploadRecordService.add(add);
//        RedisUtil.getJedis().set(newName, JSON.toJSONString(uploadedFileInfo));
//        RedisUtil.getJedis().close();

        return 0;
    }

    @GetMapping("/userStatistics")
    public String userStatistics(){
        Long all = this.userStatisticsService.getAllUserNum();
        Long time = System.currentTimeMillis();
        Long cur = this.userStatisticsService.getCurrentUserNum(time-30*60*1000, time);
        Long day = this.userStatisticsService.getCurrentUserNum(DateUtils.getDayBegin().getTime(), DateUtils.getDayEnd().getTime());
        Long week = this.userStatisticsService.getWeekUserNum(DateUtils.getBeginDayOfWeek().getTime(), DateUtils.getEndDayOfWeek().getTime());
        Long month = this.userStatisticsService.getMonthUserNum(DateUtils.getBeginDayOfMonth().getTime(), DateUtils.getEndDayOfMonth().getTime());
        request.setAttribute("all", all);
        request.setAttribute("cur", cur);
        request.setAttribute("day", day);
        request.setAttribute("week", week);
        request.setAttribute("month", month);
        return "admin/sys/pest/user_statistics";
    }

}
class UploadedFileInfo{
    private String fileName;
    private Long size;
    private String localPath;
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public Long getSize() {
        return size;
    }
    public void setSize(Long size) {
        this.size = size;
    }
    public String getLocalPath() {
        return localPath;
    }
    public void setLocalPath(String localPath) {
        this.localPath = localPath;
    }

}
